<?php
/**
 * Object Relational Persistence Mapping Class for table: dictionary
 *
 * @package	com.clearhealth
 * @author	ClearHealth Inc.
 */
class Dictionary extends ORDataObject {

	/**#@+
	 * Fields of table: dictionary mapped to class members
	 */
	var $dictionary_id		= '';
	var $user_id		= '';
	var $abbreviation		= '';
	var $replaced_text		= '';
	/**#@-*/


	/**
	 * DB Table
	 */
	var $_table = 'dictionary';

	/**
	 * Primary Key
	 */
	var $_key = 'dictionary_id';
	
	/**
	 * Internal Name
	 */
	var $_internalName = 'Dictionary';

	/**
	 * Handle instantiation
	 */
	function Dictionary() {
		parent::ORDataObject();
	}
	
	public function getAllItems($userId) {
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "dictionary_id AS id, abbreviation, replaced_text",
			'from' 		=> "$this->_table",
			'where' 	=> "user_id = $userId"
			);
					
		$ds->setup($this->_db, $sql);
		return $ds->toArray();
	}
	
	public function addNewItem($userId, $abbreviation, $replacedText) {
		$data = array (
				'user_id'      => $userId,
		        'abbreviation' => $abbreviation,
				'replaced_text'     => $replacedText								
			);		
		$this->populateArray($data);		
		return $this->persist();
	}
	
	public function getId($userId, $abbreviation) {
		$sql = "SELECT dictionary_id FROM $this->_table WHERE user_id = $userId AND abbreviation = '$abbreviation'";
		$res = $this->_execute($sql);
		if(!empty($res) && ($res->fields['dictionary_id'] != '')) {
			return $res->fields['dictionary_id'];
		}
		return 0;
	}
	
	public function getRealPersistenceInfo() {
		$sql = "SELECT abbreviation, replaced_text FROM $this->_table WHERE $this->_key = $this->dictionary_id";
		return $this->_execute($sql);
	}
	
	public function deleteItem($id) {
		$sql = "DELETE FROM $this->_table WHERE dictionary_id = $id";
		$this->_execute($sql);
	}
	
	public function getReplacedText($source, $userId) {
		$token = split(" ", $source);
		$resultSet = $this->_execute($this->buildQueryFromToken($token, $source, $userId));
		$response[0]['source'] = "";
		$response[0]['replace'] = "";
		$i = 0;
		if(!empty($resultSet)) {
			foreach($resultSet as $item) {
				$response[$i]['source'] = $item['abbreviation'];
				$response[$i]['replace'] = $item['replaced_text'];
				$i++;
			}
		}
		return $response[0];
	}
	
	private function buildQueryFromToken($token, $source, $userId) {
    	$sql = "SELECT abbreviation, replaced_text FROM dictionary WHERE user_id = $userId AND (false";
    	for ($i = count($token); $i > 0; $i--) {
			$element = split(" ", $source, $i);
			$sql .= " OR abbreviation = '" . $element[$i - 1] . "'";
		}
		$sql .= ")";
		return $sql;
    }

}
?>
